package com.qijian.tool.utils;

import cn.hutool.core.util.ObjectUtil;
import com.qijian.common.utils.StringUtils;

import javax.validation.constraints.NotEmpty;
import java.lang.reflect.Field;
import java.util.List;

public class CheckUtils {

    /**
     * 用于校验类 @NotEmpty的字段是否为空
     *
     * @param aClass
     * @param obj
     * @param line
     * @return
     * @throws IllegalAccessException
     */
    public static StringBuilder checkNotEmpty(Class aClass, Object obj, Integer line) throws IllegalAccessException {
        StringBuilder error = new StringBuilder();
        Field[] fields = aClass.getDeclaredFields();
        for (Field field : fields) {
            NotEmpty annotation = field.getAnnotation(NotEmpty.class);
            if (ObjectUtil.isNotNull(annotation)) {
                //设置允许访问私有属性
                field.setAccessible(Boolean.TRUE);

                Object value = field.get(obj);
                //判断该参数是否为空
                if (ObjectUtil.isEmpty(value)) {
                    if (null == line & ObjectUtil.equal(line, -1)) {
                        error.append(annotation.message());
                    } else {
                        error.append(StringUtils.format("第{}行" + annotation.message(), line.intValue()));
                    }

                }
            }
        }
        return error;
    }

    /**
     * 用于校验list @NotEmpty的字段是否为空
     *
     * @param aClass
     * @param objects
     * @return
     * @throws IllegalAccessException
     */
    public static String checkNotEmpty(Class aClass, List<?> objects) throws IllegalAccessException {
        StringBuilder stringBuilder = new StringBuilder();
        int line = 2;
        for (Object o : objects) {
            stringBuilder.append(checkNotEmpty(aClass, o, line));
            line++;
        }
        return stringBuilder.toString();
    }

}
